<?php

namespace backend\modules\Product\controllers;

use backend\models\c2\form\EavSkuForm;
use backend\models\c2\form\ProductPackageForm;
use common\models\c2\entity\ProductSku;
use common\models\c2\entity\ProductStock;
use common\models\c2\entity\SaleProduct;
use kartik\grid\EditableColumnAction;
use kzo\base\models\statics\ResponseDatum;
use Yii;
use common\models\c2\entity\Product;
use common\models\c2\search\ProductSearch as ProductSearch;

use kzo\base\components\controllers\backend\ModelController as Controller;
use yii\helpers\ArrayHelper;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * DefaultController implements the CRUD actions for Product model.
 */
class DefaultController extends Controller
{
    public $modelClass = 'common\models\c2\entity\SaleProduct';

    public function actions()
    {
        return ArrayHelper::merge(parent::actions(), [
            'eav-save' => [
                'class' => \common\components\actions\EavSaveAction::className(),
                'modelClass' => \backend\models\c2\form\EavForm::className(),
                'checkAccess' => [$this, 'checkAccess'],
            ],
            'sku-edit-column' => [
                'class' => \kartik\grid\EditableColumnAction::className(), // action class name
                'modelClass' => ProductSku::className(), // the update model class
            ],
        ]); // TODO: Change the autogenerated stub
    }

    /**
     * Lists all Product models.
     * @return mixed
     * @throws NotFoundHttpException
     */
    public function actionIndex()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'model' => $this->retrieveModel(),
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * create/update a Product model.
     * fit to pajax call
     * @return mixed
     * @throws NotFoundHttpException
     */
    public function actionEdit($id = null)
    {
        $model = $this->retrieveModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash($model->getMessageName(), [Yii::t('app.c2', 'Saved successful.')]);
            } else {
                Yii::$app->session->setFlash($model->getMessageName(), $model->errors);
            }
        }

        return (Yii::$app->request->isAjax) ? $this->renderAjax('edit', ['model' => $model,]) : $this->render('edit', ['model' => $model,]);
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = SaleProduct::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionGenerateSkus()
    {
        try {
            $request = Yii::$app->request;
            $params = Yii::$app->request->post();

            if (!isset($params['entity_id'])) {
                throw new HttpException(404, Yii::t('app.c2', "Missing parameter entity_id!"));
            }
            if (!isset($params['EavSkuForm'])) {
                throw new HttpException(404, Yii::t('app.c2', "Missing parameter EavSkuForm!"));
            }

            $entiyModel = $this->retrieveModel($params['entity_id']);
            $formModel = new EavSkuForm(['entityModel' => $entiyModel]);

            if ($request->isPost && Yii::$app->request->isAjax) {
                $formModel->load(Yii::$app->request->post());
            }

            // Yii::info($formModel->attributes);
            // Yii::info($params);
            /** @var $formModel EavSkuForm */
            if ($formModel->generateSkus($params['EavSkuForm'])) {
                // $responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Operation completed successfully!')]);
            }
            return (Yii::$app->request->isAjax) ? $this->renderAjax('/default/_sku_form', ['model' => $formModel]) : $this->render('edit', ['model' => $entiyModel,]);
        } catch (\Exception $ex) {
            $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Error: operation can not finish!!') . "  " . $ex->getMessage()]);
        }

        return $this->asJson($responseData);
    }

    public function actionDeleteSku($id) {
        try {
            $model = ProductSku::findOne($id);
            if ($model->delete()) {
                $responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Operation completed successfully!')], $id);
            } else {
                $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Error: operation can not finish!!')], $id);
            }
        } catch (\Exception $ex) {
            $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Error: operation can not finish!!')], $id);
        }
        return $this->asJson($responseData);
    }

    public function actionPackageEdit($id = null)
    {
        $model = $this->retrievePackageForm($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash($model->getMessageName(), [Yii::t('app.c2', 'Saved successful.')]);
            } else {
                Yii::$app->session->setFlash($model->getMessageName(), $model->errors);
            }
        }

        $model->loadItems();

        return (Yii::$app->request->isAjax) ? $this->renderAjax('_package_form', ['model' => $model,]) : $this->render('_package_form', ['model' => $model,]);
    }

    public function retrievePackageForm($id)
    {
        $product = Product::findOne($id);
        if (is_null($product)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        $model = new ProductPackageForm(['entityModel' => $product]);
        $model->loadDefaultValues();
        return $model;
    }

    public function actionDeleteSubitem($id) {
        if (($model = \common\models\c2\entity\ProductPackage::findOne($id)) !== null) {
            if ($model->delete()) {
                $responseData = ResponseDatum::getSuccessDatum(['message' => Yii::t('app.c2', 'Operation completed successfully!')], $id);
            } else {
                $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Error: operation can not finish!')], $id);
            }
        } else {
            $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Error: Model not found!')], $id);
        }
        return $this->asJson($responseData);
    }

    public function actionStockEdit($id = null)
    {
        $model = $this->retrieveStockModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash($model->getMessageName(), [Yii::t('app.c2', 'Saved successful.')]);
            } else {
                Yii::$app->session->setFlash($model->getMessageName(), $model->errors);
            }
        }

        return (Yii::$app->request->isAjax) ? $this->renderAjax('_stock_form', ['model' => $model,]) : $this->render('_stock_form', ['model' => $model,]);
    }

    public function retrieveStockModel($id)
    {
        $model = ProductStock::findOne($id);
        if (!is_null($model)) {
            return $model;
        }
        $model = new ProductStock();
        $model->loadDefaultValues();
        return $model;
    }

}
